package com.qianya.system.manage.web.sys.controller;

import com.qianya.model.common.CommonResult;
import com.qianya.model.common.ResultCode;
import com.qianya.system.manage.util.MysqlBackUpUtils;
import com.qianya.util.FileManage;
import com.qianya.util.FileUtil;
import com.qianya.util.SystemConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/sys/database")
@Slf4j
@Api(value = "DataBaseBackUpController",tags = "数据库备份接口")
public class DataBaseBackUpController {
    @Autowired
    private MysqlBackUpUtils mysqlBackUpUtils;

    @PostMapping(value = "/backup")
    @ApiOperation("备份数据库")
    public CommonResult backup(){
        try {
            mysqlBackUpUtils.backup();
            return CommonResult.success();
        } catch (SQLException e) {
            return CommonResult.error(ResultCode.ERROR,"数据库备份异常");
        }
    }

    @GetMapping(value = "/recover")
    @ApiOperation("还原数据库")
    public CommonResult recover(@ApiParam(value = "文件地址",required = true)
                                    @NotBlank(message = "文件地址不能为空" )
                                    @RequestParam(defaultValue = "",name = "path") String path){
        try {
            mysqlBackUpUtils.backup(); //还原之前自动备份一次
            mysqlBackUpUtils.recover(SystemConfig.filePath() + path);
            return CommonResult.success();
        } catch (SQLException e) {
            return CommonResult.error(ResultCode.ERROR,"数据库还原异常");
        }
    }

    @GetMapping(value = "/list")
    @ApiOperation("获取文件列表")
    public Object list(){
        String filesPath=SystemConfig.filePath();
        List<FileManage> files = FileUtil.getSqlFiles(filesPath + "database");
        Collections.reverse(files);
        for (int i = 0; i <files.size() ; i++) {
            files.get(i).setStaticPath(filesPath);
        }
        return CommonResult.success(files);
    }

    /*@GetMapping(value = "/download")
    @ApiOperation("下载文件")
    public Object download(String filePath){
        try {
            return FileUtil.downloadFile(SystemConfig.filePath() + filePath);
        } catch (IOException e) {
            log.error("下载文件异常===>" + e.getMessage());
            return CommonResult.error(ResultCode.ERROR,"下载文件");
        }
    }*/
    
}
